<template>
  <div class="Home" v-loading.fullscreen="fullscreenLoading">
    <div class="canvas-con">
      <ThreeCanvas></ThreeCanvas>
    </div>
    <div class="right-con">
      <ViewSwitch></ViewSwitch>
      <CommandInput></CommandInput>
      <Log></Log>
    </div>
    <div class="roomInfo" v-if="roomId">
      <div class="roomId">房间ID：{{ $store.state.roomid }}</div>
      <img :src="require('../assets/img/copy.png')" alt="复制房间号" title="复制房间号" @click="copyRoomid()" />
      <img :src="require('../assets/img/exit.png')" alt="退出房间" title="退出房间" @click="exitRoom()" />
    </div>
    <div class="hiddenInput">
      <input type="text" :value="$store.state.roomid" id="hiddenInput" />
    </div>
  </div>
</template>

<script>
import ADDRESS from '../assets/backendApi'

import ThreeCanvas from '../components/ThreeCanvas.vue'
import ViewSwitch from '../components/ViewSwitch.vue'
import CommandInput from '../components/CommandInput.vue'
import Log from '../components/Log.vue'

import { closeWs, connectWs } from '../utils/WebSocket'

import { SET_USERNAME, SET_ROOMID, SET_OFFLINE } from '../store/events'

export default {
  name: 'Home',
  components: {
    ThreeCanvas,
    ViewSwitch,
    CommandInput,
    Log
  },
  data() {
    return {
      fullscreenLoading: true //设置一个方法，等页面加载完毕，将此值由true改为false
    }
  },
  watch: {
    '$store.state.wsState': {
      handler(val) {
        if (val === 2) {
          this.fullscreenLoading = false
        }
      },
      immediate: true
    }
  },
  computed: {
    roomId() {
      return this.$store.state.roomId ? this.$store.state.roomId : 'ID'
    }
  },
  mounted() {
    if (this.$store.state.offline) {
      this.fullscreenLoading = false
      this.$toast.success('欢迎进入离线模式！')
    } else if (this.$store.state.roomid === '') {
      const roomid = window.localStorage.getItem('roomid')
      if (roomid && roomid !== '') {
        const username = window.localStorage.getItem('username')
        fetch(ADDRESS.http + `/searchRoom/search`, {
          method: 'post',
          headers: {
            'Content-type': 'application/json'
          },
          body: JSON.stringify({
            roomId: roomid,
            userName: username
          })
        })
          .then(r => r.text())
          .then(d => {
            d = JSON.parse(d)
            if (d.status === 200) {
              this.$store.dispatch(SET_USERNAME, {
                username
              })
              this.$store.dispatch(SET_ROOMID, {
                roomid
              })
              connectWs()
              this.$toast.success('欢迎回来！')
            } else if (d.status === 403) {
              this.$router.push({
                path: '/joinHome'
              })
              this.$toast.warning('您的昵称被占用，请修改昵称！')
            } else if (d.status === 400) {
              this.$router.push({
                path: '/'
              })
              this.$toast.warning('房间已被解散！')
            } else {
              this.$router.push({
                path: '/'
              })
              this.$toast.error('回到房间失败！')
            }
          })
          .catch(e => console.error(e))
      } else {
        this.$router.push({
          path: '/'
        })
      }
    } else {
      connectWs()
    }
  },
  beforeDestroy() {
    closeWs()
  },
  beforeRouteEnter(to, from, next) {
    const { offline } = to.params
    const checkOfflineOrNot = vm => {
      vm.$store.dispatch(SET_OFFLINE, { offline: offline ? true : false })
      if (offline) {
        vm.$store.dispatch(SET_USERNAME, { username: '本地用户' })
        vm.$store.dispatch(SET_ROOMID, { roomid: '本地房间' })
      }
    }
    next(checkOfflineOrNot)
  },
  beforeRouteLeave(to, from, next) {
    this.$store.dispatch(SET_OFFLINE, { offline: false })
    this.$store.dispatch(SET_ROOMID, { roomid: '' })
    this.$store.dispatch(SET_USERNAME, { username: '' })
    next()
  },
  methods: {
    copyRoomid() {
      const hiddenInput = document.getElementById('hiddenInput')
      hiddenInput.select()
      if (document.execCommand('copy')) {
        this.$toast.success('成功复制房间号')
      } else {
        this.$toast.error('复制失败，请手动复制')
      }
    },
    exitRoom() {
      this.$store.dispatch(SET_ROOMID, { roomid: '' })
      closeWs()
      this.$router.replace({
        path: '/exit'
      })
    }
  }
}
</script>

<style scoped>
.Home {
  position: relative;
}
.canvas-con {
  width: 70vw;
  height: 100vh;
}
.right-con {
  position: absolute;
  top: 0;
  right: 0;

  width: 30vw;
  height: 100vh;

  display: flex;
  flex-direction: column;
  background-color: #fff;
}
.right-con > div {
  box-sizing: border-box;
}
.right-con > div:nth-child(1) {
  background-color: rgb(255, 246, 235);
}
.right-con > div:nth-child(3) {
  flex: 1;
  height: 0;
}
.roomInfo {
  position: absolute;
  z-index: 999;
  top: 0;
  left: 50%;
  transform: translateX(-50%);
  background-color: #55a8cc;
  color: white;
  padding: 5px 10px;
  border-radius: 0 0 5px 5px;
}
.roomId {
  display: inline;
  vertical-align: middle;
  margin: 0 6px 0 0;
}
.roomInfo > img {
  height: 1em;
  vertical-align: middle;
  margin: 0 3px;
  cursor: pointer;
}
.hiddenInput {
  position: absolute;
  top: 0;
  right: 0;
  z-index: -1;
  opacity: 0;
}
</style>
